#include "stm32f10x.h"                  // Device header
#include "HX711.h"
#include "OLED.h"

void HX711_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    GPIO_InitStruct.GPIO_Pin = HX711_SCK_PIN;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(HX711_SCK_PORT, &GPIO_InitStruct);

    GPIO_InitStruct.GPIO_Pin = HX711_DT_PIN;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_Init(HX711_DT_PORT, &GPIO_InitStruct);
}

int32_t HX711_Read(void)
{
    uint32_t value = 0;


    while (GPIO_ReadInputDataBit(HX711_DT_PORT, HX711_DT_PIN));

    for (int i = 0; i < 24; i++)
    {
        GPIO_SetBits(HX711_SCK_PORT, HX711_SCK_PIN);
        GPIO_ResetBits(HX711_SCK_PORT, HX711_SCK_PIN);

        value = (value << 1) | GPIO_ReadInputDataBit(HX711_DT_PORT, HX711_DT_PIN);
    }

    for (int i = 0; i < 1; i++)
    {
        GPIO_SetBits(HX711_SCK_PORT, HX711_SCK_PIN);
        GPIO_ResetBits(HX711_SCK_PORT, HX711_SCK_PIN);
    }

    if (value & 0x800000)
    {
        value |= 0xFF000000;
    }
//	OLED_ShowNum(2, 1, value, 7);
    return (int32_t)value;
}

void HX711_Calibrate(int32_t* offset, float* scale)
{
    *offset = HX711_Read();
     float weight2=98,weight1=34;
		float value2=722930,value1=694380;
    *scale = (weight2 - weight1) / (value2 - value1)+0.00011;
}

float HX711_GetWeight(int32_t offset, float scale)
{
    int32_t sensorValue = HX711_Read();
	int32_t scale1;
    float weight = (sensorValue - offset)*scale;scale1=-scale*10000;
//	OLED_ShowNum(4,1,(int)scale1,8);
//	OLED_ShowNum(3,1,(int)weight,5);
    return weight;
}


